package com.phz.springcloud.study.service;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import feign.FeignException;

/**
 * 消息订阅者
 * 
 * @author penghaozhong
 *
 */
@Component
@RabbitListener(queues = "register-score-queue")
public class RegisterGeScoreReceiver {

	protected static final Logger logger = LoggerFactory.getLogger(RegisterGeScoreReceiver.class);

	private static final ObjectMapper mapper = new ObjectMapper();

	@Autowired
	private AccoutService accoutService;

	@RabbitHandler
	private String process(String user) throws RateLimitException  {
		JsonNode jsonNode;
		String phone = null;
		String userName = null;
		
			try {
				jsonNode = mapper.readValue(user, JsonNode.class);
				if (jsonNode.get("phone") != null) {
					phone = jsonNode.get("phone").asText();
					userName = jsonNode.get("username").asText();
					return accoutService.saveAccoutInfoGeCuccScore(phone, userName);
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (FeignException e) {
				throw new RateLimitException(e.getMessage());
			}
			
			return null;
	}

}
